package cn.com.yto56.coresystem.business.msg.mc.job;

import cn.com.yto56.coresystem.business.msg.mc.biz.impl.MsgChannelManager;
import cn.com.yto56.coresystem.business.msg.mc.util.MsgResult;
import cn.com.yto56.coresystem.common.msg.util.base.StringUtils;
import cn.com.yto56.coresystem.common.msg.util.domain.AppResult;
import cn.com.yto56.coresystem.common.msg.util.io.AppConfigurationUtil;
import cn.com.yto56.coresystem.msg.client.YtoMsgServiceClient;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by wangrui on 2017/5/3.
 */
@Component
public class MsgJob {
    private static final Logger logger = LoggerFactory.getLogger(MsgJob.class);
    @Autowired
    private MsgChannelManager msgChannelManager;
    //SOA消息服务
    private static YtoMsgServiceClient ytoMsgServiceClient;

    static {
        String url = AppConfigurationUtil.getPropertyValue("msg.soa.url");
        String REQUEST_TYPE = AppConfigurationUtil.getPropertyValue("msg.soa.type");
        try {
            ytoMsgServiceClient = new YtoMsgServiceClient(url, REQUEST_TYPE);
        } catch (MalformedURLException e) {
            logger.error("SOA客户端初始化失败", e);
        }
    }

    /**
     * 清除临时client
     */
    @Scheduled(cron = "0/30 * * * * ? ")
    public void removeTempChannel() {
        msgChannelManager.removeTempChannel(new Date());
    }


    /**
     * 推送消息
     */
    @Scheduled(cron = "0/10 * * * * ? ")
    public void sendMsg() {
        MsgResult msgResult = new MsgResult();
        //TODO 效率低  目标通过内存解决  自己管理内存
        for (int i = 0; i < msgChannelManager.channelManagerBeanList.size(); i++) {
            String clientId = msgChannelManager.channelManagerBeanList.get(i).getClientId();
            if (StringUtils.isNotBlank(clientId) && !clientId.startsWith("mc_temp_")) {
                String[] params = clientId.split("\\|");
                String appId = params[2];
                String userId = params[1];
                ytoMsgServiceClient.bindAppId(appId);
                AppResult appResult = ytoMsgServiceClient.getCurrentMSG(userId, new SimpleDateFormat("yyyy-MM-dd 23:59:59").format(new Date()));
                if (appResult.getDatas() != null && ((List) appResult.getDatas()).size() > 0) {
                    String responseJson = msgResult.getRequestJson("ytoMsgService.sendMsg", appId, appResult.getDatas());
                    //推送消息
                    if (StringUtils.isNotBlank(responseJson)) {
                        ByteBuf buf = null;
                        try {
                            buf = Unpooled.buffer(responseJson.getBytes("UTF-8").length);
                            buf.writeBytes(responseJson.getBytes("UTF-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        msgChannelManager.channelManagerBeanList.get(i).getChannel().writeAndFlush(buf);
                    }
                }
            }
        }
    }


    /**
     * 重发机制
     */
    public void reSendMsg() {

    }
}
